package com.devicemantra.coordinate.ds.tests;
import com.devicemantra.coordinate.dataobjects.*;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.devicemantra.coordinate.dataobjects.CDepartmentFactory;
import com.devicemantra.coordinate.exceptions.operations.CDepartmentDoesNotExistsException;
import com.devicemantra.coordinate.interfaces.sms.SMS;
import com.devicemantra.coordinate.interfaces.sms.SMSFactory;
import com.devicemantra.coordinate.util.*;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;

@SuppressWarnings("serial")
public class GetFrames extends HttpServlet 
{
	private List<CLocation> lLocationList = null;
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException 
	{
		resp.setContentType("text/xml");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String lDeptName = (String) req.getParameter("dept_name");
		String lEmirateName = (String) req.getParameter("emirate");
		
		
		/* Testing code to trigger sending sms */
		/*System.out.println("SMS Sending test starts here");
		SMS lNewSms = SMSFactory.creatNewSMS();
		lNewSms.setMobileNumber("971559266628");
		lNewSms.setMessage("Welcome to the CoOrdinate system");
		lNewSms.setLanguage(0);
		SMSFactory.sendSMS(lNewSms);
		
		SMS lNewSms1 = SMSFactory.creatNewSMS();
		lNewSms1.setMobileNumber("971501325042");
		lNewSms1.setMessage("Welcome to the CoOrdinate system");
		lNewSms1.setLanguage(0);
		SMSFactory.sendSMS(lNewSms1); */ 
		
		if( (null == lDeptName ) && (null == lEmirateName))
		{
			System.out.println("Error : Either Emirate or Department must be selected");
			return;
		}
		System.out.println("GetFrames called Deptname " + lDeptName + " Emirate " + lEmirateName);
		
		
		/* Check if this a query for dept_name also mentioned is the emirate */
		if( (lDeptName != null) && (lEmirateName != null ) )
		{
			System.out.println("Calling getFrameList(" + lDeptName + "," + lEmirateName + ")" );
			lLocationList = getFrameList(lDeptName, lEmirateName);
		}
		
		if(null == lDeptName)
		{ 
			javax.jdo.Query query = pm.newQuery(CLocation.class);
			query.setFilter("mEmirate == lEmirateName");
			query.declareParameters("String lEmirateName");
		    lLocationList = (List<CLocation>) query.execute(lEmirateName);
		    System.out.println("Number of frames found " + lLocationList.size());	
			
		}
		else if(lEmirateName == null)
		{
			try {
				lLocationList = CDepartmentFactory.getDepartment(lDeptName).getLocations();
			} catch (CDepartmentDoesNotExistsException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("Number of frames for department " + lDeptName + " " + lLocationList.size());
		}
		
		
		
		if(lLocationList == null)
		{
			System.out.println("ERROR: Empty result set");
			return;
		}
		String lXmlStr = getInfoAsXml(lLocationList);
		System.out.println("XML :" + lXmlStr );
		resp.getOutputStream().println(lXmlStr);
	}
	
	public List<CLocation> getAllDeptsAllEmirates()
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.getFetchPlan().setMaxFetchDepth(3);
	    List<CLocation> lLocationList = null;
	    javax.jdo.Query query = pm.newQuery(CLocation.class);
		/*query.setFilter("mDestinationFrameId == lCFrameId");
		query.setFilter("mIsRead == lIsTrue"); */
		//query.declareParameters("String lCFrameId, boolean lGiveReadMessages");
	    lLocationList = (List<CLocation>) query.execute();
	    lLocationList = (List<CLocation>)pm.detachCopyAll(lLocationList);
	    System.out.println("Number of frames found  for " + lLocationList.size());
		pm.close();
		return lLocationList;
	}
	
	public List<CLocation> getAllDeptsParticularEmirate(String pEmirate)
	{
		 PersistenceManager pm = PMF.get().getPersistenceManager();
		 List<CLocation> lLocationList = null;
		 pm.getFetchPlan().setMaxFetchDepth(3);
		 javax.jdo.Query query = pm.newQuery(CLocation.class, "mEmirate == pEmirate");
		 /*query.setFilter("mDestinationFrameId == lCFrameId");
		 query.setFilter("mIsRead == lIsTrue"); */
		 query.declareParameters("String pEmirate");
		 lLocationList = (List<CLocation>) query.execute(pEmirate);
		 lLocationList = (List<CLocation>)pm.detachCopyAll(lLocationList);
		 //pm.retrieveAll(lCFrameList);
		 System.out.println("Number of frames found  for " + pEmirate + " is "  +  lLocationList.size());
		 pm.close();
		 return lLocationList;
		
	}
	
	public List<CLocation> getAllEmiratesParticularDept(String pDeptName)
	{
		CDepartment lDept = null;
		try {
			lDept = CDepartmentFactory.getDepartment(pDeptName);
		} catch (CDepartmentDoesNotExistsException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		List<CLocation> lLocationList = lDept.getLocations();
		System.out.println("Number of frames found  for " + pDeptName + " is "  +  lLocationList.size());
		return lLocationList;
		
	}
	
	public List<CLocation> getParticularDeptForParticularEmirate(String lDept, String lEmirate)
	{
		List<CLocation> lLocationList = getAllDeptsParticularEmirate(lEmirate);
		System.out.println("Number of frames for Emirate is " + lEmirate + " " + lLocationList.size());
		System.out.println("Printing retreived list now");
		printList(lLocationList);
		int lLengthOfList = lLocationList.size();
		List<CLocation> lNewLocationList = new ArrayList<CLocation>();
		for(int lCounter = 0; lCounter < lLengthOfList; lCounter++ )
		{
			CLocation lCFrame = lLocationList.get(lCounter);
			System.out.println("List size is " + lLocationList.size());
			System.out.println("Checking department " + lCFrame.getOwningDepartment().getDepartmentName() + " with " + lDept);
			if(lCFrame.getOwningDepartment().getDepartmentName().equals(lDept))
			{
				System.out.println("Checking  dept - " + lCFrame.getOwningDepartment().getDepartmentName());
				lNewLocationList.add(lCFrame);
				continue;
			}
			else
			{
				System.out.println("Removing dept - " + lCFrame.getOwningDepartment().getDepartmentName());
				//lFrameList.remove(lCounter);
			}
		}
		System.out.println("Returning list of size " + lLocationList.size());
		return lNewLocationList;
	}
	
	private List<CLocation> getFrameList(String pDeptName, String pEmirate)
	{
		List<CLocation> lLocationList = null;
		if(pDeptName.equals("ALL") && pEmirate.equals("ALL"))
		{
			/* Request is for all the frames from different depts in all the states */
			lLocationList = getAllDeptsAllEmirates();
			System.out.println("ALL Departments ALL Emirates");
		}
		
		if(pDeptName.equals("ALL") && !(pEmirate.equals("ALL")))
		{
			/* Request is for all the frames from different depts in a particular state */
			lLocationList = getAllDeptsParticularEmirate(pEmirate);
			System.out.println("ALL Departments Particular Emirate " + pEmirate);
		}
		
		if( !(pDeptName.equals("ALL")) && pEmirate.equals("ALL"))
		{
			/* Request is for all the frames from different depts in a particular state */
			lLocationList =  getAllEmiratesParticularDept(pDeptName);
			System.out.println("ALL Emirate Particular Department " + pDeptName);
		}
		
		if( !(pDeptName.equals("ALL")) && !(pEmirate.equals("ALL")) )
		{
			/* Request is for all the frames from different depts in a particular state */
			System.out.println("Callingg Particular Emirate Particular Department " + pDeptName + " " + pEmirate);
			lLocationList = getParticularDeptForParticularEmirate(pDeptName, pEmirate);
			printList(lLocationList);
			System.out.println("Particular Emirate Particular Department " + pDeptName);
		}
		
		//printList(lCFrameList);
		return lLocationList;
	}
	
	
	
	
	
	public String getInfoAsXml(List<CLocation> lLocationList)
	{
		
		CXMLBuilder lXmlBuilder = new CXMLBuilder();
		/* First task is to get the url for the department logo */
		//Department lDept = DepartmentFactory.getDepartment(pFrame.getOwningDepartment());
		
		/* Start building the xml */
		lXmlBuilder.AddOpeningTag("xml");
		for(int lCounter = 0; lCounter < lLocationList.size(); lCounter++)
		{
			CLocation lLocation = lLocationList.get(lCounter);
			lXmlBuilder.AddOpeningTag("CLocation");
			lXmlBuilder.AddNode("CFrameId", lLocation.getLocationId());
			lXmlBuilder.AddNode("CLat", lLocation.getLocation().getLatitude().toString());
			lXmlBuilder.AddNode("CLong", lLocation.getLocation().getLongitude().toString());
			lXmlBuilder.AddNode("CEmirate", lLocation.getEmirate());
			lXmlBuilder.AddNode("CAddress", lLocation.getAddress());
			lXmlBuilder.AddNode("CDepartment", lLocation.getOwningDepartment().getDepartmentName());
			System.out.println("Department " + lLocation.getOwningDepartment().getDepartmentName());
			lXmlBuilder.AddNode("CDepartmentLogo", lLocation.getOwningDepartment().getLogo().getUrl());
			if(lLocation.getLocationDescription().length() == 0)
			{
				lLocation.setLocationDescription("NA");
			}
			lXmlBuilder.AddNode("CDescription", lLocation.getLocationDescription());
			lXmlBuilder.AddClosingTag("CLocation");
		}
		
		lXmlBuilder.AddClosingTag("xml");
		return lXmlBuilder.getXml();
	}
	
	public void printList(List<CLocation> pLocationList)
	{
		for(int lCounter = 0; lCounter < pLocationList.size(); lCounter++)
		{
			System.out.println("-------------------------");
			System.out.println("Frame id is " + pLocationList.get(lCounter).getLocationId());
			System.out.println("Frame department is " + pLocationList.get(lCounter).getOwningDepartment().getDepartmentName());
			System.out.println("-------------------------");
		}
	}
	
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException 
	{
		doPost(req,resp);
	}
}
